<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px flex">
      <el-button
        class="ml-12px"
        v-if="
          ![20, 30, 40, 50, 60].includes(formData.dictQualityImproveStatus) &&
          !formType.includes('view')
        "
        type="primary"
        @click="submitForm(10)"
        v-hasPermi="['quality:improvement:save']"
        :loading="loading"
      >
        保 存
      </el-button>
      <el-button
        class="ml-12px"
        v-if="
          ![20, 30, 40, 50, 60].includes(formData.dictQualityImproveStatus) &&
          !formType.includes('view')
        "
        type="primary"
        @click="submitForm(30)"
        v-hasPermi="['quality:improvement:submit']"
        :loading="formLoading"
      >
        提 交
      </el-button>
      <el-button
        class="ml-12px"
        @click="submitForm(60)"
        v-if="
          ![20, 30, 40, 50, 60].includes(formData.dictQualityImproveStatus) &&
          !formType.includes('view')
        "
        type="danger"
        v-hasPermi="['quality:improvement:cancel']"
        :loading="formLoading"
        >作 废</el-button
      >
      <el-button
        class="ml-12px"
        @click="submitForm(10)"
        v-if="![10, 20].includes(formData.dictQualityImproveStatus) && formType.includes('update')"
        type="danger"
        v-hasPermi="['quality:improvement:recall']"
        :loading="formLoading"
        >撤 回</el-button
      >
      <el-button
        class="ml-12px"
        @click="submitForm(50)"
        v-if="![10, 30].includes(formData.dictQualityImproveStatus) && formType.includes('update')"
        type="primary"
        v-hasPermi="['quality:improvement:adopt']"
        :loading="formLoading"
        >通 过</el-button
      >
      <el-button
        class="ml-12px"
        @click="submitForm(40)"
        v-if="![10, 30].includes(formData.dictQualityImproveStatus) && formType.includes('update')"
        type="danger"
        v-hasPermi="['quality:improvement:reject']"
        :loading="formLoading"
        >驳 回</el-button
      >
      <el-button class="ml-12px" @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :inline="true"
        label-width="150px"
        v-loading="formLoading"
      >
        <el-form-item label="品质改善编号" prop="qualityImproveCode">
          <el-input disabled v-model="formData.qualityImproveCode" placeholder="品质改善编号" />
        </el-form-item>
        <el-form-item label="产品编号" prop="productCode">
          <el-input
            :disabled="
              formType.includes('view') || [20, 30].includes(formData.dictQualityImproveStatus)
            "
            v-model="formData.productCode"
            placeholder="请输入产品编号"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            :disabled="
              formType.includes('view') || [20, 30].includes(formData.dictQualityImproveStatus)
            "
            v-model="formData.productName"
            placeholder="请输入产品名称"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            :disabled="
              formType.includes('view') || [20, 30].includes(formData.dictQualityImproveStatus)
            "
            v-model="formData.customerName"
            placeholder="请输入客户名称"
          />
        </el-form-item>

        <el-form-item label="故障来源" prop="dictFaultSource">
          <el-select
            :disabled="
              formType.includes('view') || [20, 30].includes(formData.dictQualityImproveStatus)
            "
            v-model="formData.dictFaultSource"
            placeholder="请选择故障来源"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions('dict_fault_source')"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="反馈时间" prop="feedbackTime">
          <el-date-picker
            :disabled="
              formType.includes('view') || [20, 30].includes(formData.dictQualityImproveStatus)
            "
            v-model="formData.feedbackTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择反馈时间"
          />
        </el-form-item>
        <el-form-item label="处理部门" prop="deptName">
          <el-select
            :disabled="formType.includes('view')"
            v-model="formData.deptName"
            filterable
            remote
            reserve-keyword
            placeholder="请选择处理部门"
            remote-show-suffix
            :remote-method="getSelectDeptList"
            :loading="deptLoading"
          >
            <el-option
              v-for="(item, index) in department"
              :key="index"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="handlerName">
          <el-select
            :disabled="formType.includes('view')"
            v-model="formData.handlerName"
            filterable
            remote
            reserve-keyword
            placeholder="请选择处理人"
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="methodLoading"
            :suffix-icon="Search"
          >
            <el-option
              v-for="(item, index) in optionsHandler"
              :key="index"
              :label="item.staffName"
              :value="item.staffName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理截止日期" prop="deadline">
          <el-date-picker
            :disabled="formType.includes('view')"
            v-model="formData.deadline"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择处理截止日期"
          />
        </el-form-item>
        <el-form-item label="故障类别" prop="dictFaultType">
          <el-select
            :disabled="
              formType.includes('view') || [20, 30].includes(formData.dictQualityImproveStatus)
            "
            v-model="formData.dictFaultType"
            placeholder="请选择故障类别"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions('dict_fault_type')"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="问题描述" prop="problemDescription" style="width: 100%">
          <el-input
            :disabled="
              [20, 30].includes(formData.dictQualityImproveStatus) || formType.includes('view')
            "
            v-model="formData.problemDescription"
            placeholder="请输入问题描述"
            type="textarea"
            maxlength="200"
            show-word-limit
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="原因分析" prop="causeAnalysis" style="width: 100%">
          <el-input
            disabled
            v-model="formData.causeAnalysis"
            placeholder="请输入原因分析"
            type="textarea"
            show-word-limit
            maxlength="200"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="临时措施" prop="temporaryMeasure" style="width: 100%">
          <el-input
            disabled
            v-model="formData.temporaryMeasure"
            placeholder="请输入临时措施"
            type="textarea"
            show-word-limit
            maxlength="200"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="纠正措施" prop="correctiveMeasure" style="width: 100%">
          <el-input
            disabled
            v-model="formData.correctiveMeasure"
            placeholder="请输入纠正措施"
            type="textarea"
            show-word-limit
            maxlength="200"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="预防措施" prop="preventiveMeasure" style="width: 100%">
          <el-input
            disabled
            v-model="formData.preventiveMeasure"
            placeholder="请输入预防措施"
            type="textarea"
            show-word-limit
            maxlength="200"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="沟通记录" prop="communicationRecord" style="width: 100%">
          <el-input
            :disabled="formType.includes('view')"
            v-model="formData.communicationRecord"
            placeholder="请输入沟通记录"
            type="textarea"
            show-word-limit
            maxlength="200"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="附件上传" prop="fileId" v-if="!formType.includes('view')">
          <UploadFile
            v-model="fileList"
            :limit="1"
            :fileSize="200"
            :fileType="['pdf', 'png', 'jpg']"
            @update:modelValue="uploadFileRes"
          />
        </el-form-item>
        <el-form-item label="附件名称" prop="fileName" v-else>
          <el-button
            v-if="formData.fileName"
            type="primary"
            @click="openFile(formData.filePath)"
            link
            >{{ formData.fileName }}</el-button
          >
        </el-form-item>
        <el-form-item label="效果验证" prop="effectVerify" style="width: 100%">
          <el-input
            :disabled="
              ![20].includes(formData.dictQualityImproveStatus) || formType.includes('view')
            "
            v-model="formData.effectVerify"
            placeholder="请输入效果验证"
            type="textarea"
            show-word-limit
            maxlength="200"
            style="width: 80%"
          />
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as ImprovementApi from '@/api/quality/qualitycontrol/improvement'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as componentApi from '@/api/componentApi'
import { Search } from '@element-plus/icons-vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const fileList = ref<any[]>([])
const optionsHandler = ref<any[]>([]) // 处理人
const department = ref<any[]>([]) // 处理部门

const loading = ref(false)
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  qualityImproveCode: undefined,
  productCode: undefined,
  productName: undefined,
  customerName: undefined,
  dictFaultSource: undefined,
  deptId: undefined,
  deptName: undefined,
  feedbackTime: undefined,
  handlerId: undefined,
  handlerName: undefined,
  dictFaultType: undefined,
  deadline: undefined,
  problemDescription: undefined,
  causeAnalysis: undefined,
  temporaryMeasure: undefined,
  correctiveMeasure: undefined,
  preventiveMeasure: undefined,
  communicationRecord: undefined,
  fileId: undefined,
  fileName: '',
  filePath: '',
  dictQualityImproveStatus: undefined as any,
  effectVerify: undefined,
  submitFlag: undefined
})
const formRules = reactive({
  deptId: [{ required: true, message: '处理部门ID不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '处理部门名称不能为空', trigger: 'blur' }],
  handlerName: [{ required: true, message: '处理人名称不能为空', trigger: 'blur' }],
  deadline: [{ required: true, message: '处理截止日期不能为空', trigger: 'blur' }],
  dictQualityImproveStatus: [{ required: true, message: '品质改善状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const { query } = useRoute() // 路由的查询
/** 打开弹窗 */
const getData = async () => {
  formType.value = (query as any).type
  resetForm()
  if (query.id) {
    formLoading.value = true
    try {
      formData.value = await ImprovementApi.getImprovement((query as any).id)
      if (formData.value.fileName != '') {
        fileList.value.push({
          name: formData.value.fileName,
          url: formData.value.filePath
        })
      }
    } finally {
      formLoading.value = false
    }
  }
}

// 处理人
const methodLoading = ref(false)
const remoteMethod = async (keyword: string) => {
  methodLoading.value = true
  try {
    const data = await componentApi.getStaffList(keyword)
    optionsHandler.value = data
  } finally {
    methodLoading.value = false
  }
}

// 处理部门
const deptLoading = ref(false)
const getSelectDeptList = async (keyword: string) => {
  deptLoading.value = true
  try {
    const data = await componentApi.getDeptList(keyword)
    department.value = data
  } finally {
    deptLoading.value = false
  }
}

// 查看文件
const openFile = (path: string) => {
  if (!path) {
    message.notifyError('附件不存在!')
    return
  }
  window.open(path)
}

// 改善编号
// const getImproveCode = async () => {
//   loading.value = true
//   try {
//     const data = await ImprovementApi.createSave()
//     formData.value.qualityImproveCode = data
//   } finally {
//     loading.value = false
//   }
// }

/** 提交表单 */
const submitForm = async (val: number) => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ImprovementApi.ImprovementVO
    if (data.dictQualityImproveStatus === 20) {
      if (!data.effectVerify) {
        message.notifyError('请输入效果验证!')
        return
      }
    }
    data.dictQualityImproveStatus = val
    if (!data.deptId) {
      department.value.map((item) => {
        if (item.name == data.deptName) {
          data.deptId = item.id
        }
      })
    }
    if (!data.handlerId) {
      optionsHandler.value.map((item) => {
        if (item.staffName == data.handlerName) {
          data.handlerId = item.id
        }
      })
    }
    if (formType.value === 'create') {
      await ImprovementApi.createSave(data)
      message.success(t('common.createSuccess'))
      goBack()
    } else {
      await ImprovementApi.updateImprovement(data)
      message.success(t('common.updateSuccess'))
      goBack()
    }
  } finally {
    formLoading.value = false
  }
}

/**文件上传返回 */
const uploadFileRes = (data) => {
  if (JSON.parse(data).length) {
    const res = JSON.parse(data)
    formData.value.fileName = res[0].name
    formData.value.filePath = res[0].url
  } else {
    fileList.value = []
    formData.value.fileName = ''
    formData.value.filePath = ''
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    qualityImproveCode: undefined,
    productCode: undefined,
    productName: undefined,
    customerName: undefined,
    dictFaultSource: undefined,
    deptId: undefined,
    deptName: undefined,
    feedbackTime: undefined,
    handlerId: undefined,
    handlerName: undefined,
    dictFaultType: undefined,
    deadline: undefined,
    problemDescription: undefined,
    causeAnalysis: undefined,
    temporaryMeasure: undefined,
    correctiveMeasure: undefined,
    preventiveMeasure: undefined,
    communicationRecord: undefined,
    fileId: undefined,
    fileName: '',
    filePath: '',
    dictQualityImproveStatus: undefined as any,
    effectVerify: undefined,
    submitFlag: undefined
  }
  formRef.value?.resetFields()
}

/** 关闭 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path: '/quality/quality/qualitycontrol/quality-improvement'
  })
}

const contentHeight = ref(0)
onMounted(() => {
  contentHeight.value = document.body.clientHeight - 127
  getData()
})
</script>
